package com.woniu.config;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.woniu.outlet.dao.UserPoMapper;
import com.woniu.outlet.dao.WorkerMapper;
import com.woniu.util.JwtTokenUtil;
import com.woniu.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 自定义认证成功处理器
 */
@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WorkerMapper workerMapper;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try {
            String username = request.getParameter("username");
            String tokenStr = JwtTokenUtil.createSign(username);
            ValueOperations<String,String> ops = redisTemplate.opsForValue();
            Object o = ops.get("percoode:" + username);
            if(StringUtils.isEmpty(o)){
                List<String> percodes=workerMapper.getPercodeByUsername(username);
                ops.set("percode:"+username,objectMapper.writeValueAsString(percodes));
            }
            //定义用于响应输出的结果对象
            ResponseResult success= new ResponseResult<String>(tokenStr, "登录成功",200);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            //利用jackon转json串的方法
            writer.write(new ObjectMapper().writeValueAsString(success));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
